package com.example.service;

import com.example.entity.PhotoDTO;
import com.example.entity.TNotes;
import com.example.mapper.TNotesMapper;
import com.example.utils.OssUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Service
public class TNotesService {
    @Resource
    private TNotesMapper tNotesMapper;

    @Resource
    private OssUtil ossUtil;

    /**
     * 发布帖子，包含图片上传和文字信息存储
     * @param tNotes 帖子信息
     * @param file 图片文件
     */
    @Transactional
    public void add(TNotes tNotes, MultipartFile file) throws IOException {
        // 1. 先插入帖子基本信息,获取生成的nid
        tNotes.setCreatedDate(new Timestamp(new Date().getTime()));
        tNotes.setUpdatedDate(new Timestamp(new Date().getTime())); 
        tNotesMapper.add(tNotes);
        
        // 2. 上传图片到OSS
        String imgUrl = ossUtil.uploadImage(file, "Photo");

        /**
         * 异步处理上传的图片
         * 和数据库中的图片匹配
         */

        // 3. 插入图片信息,关联nid
        PhotoDTO photo = new PhotoDTO();
        photo.setUid(tNotes.getUid());
        photo.setNid(tNotes.getNid()); // 关联帖子ID
        photo.setType(0);
        photo.setImgUrl(imgUrl);
        photo.setUploadTime(new Timestamp(new Date().getTime()));
        tNotesMapper.addPhoto(photo);
        
        // 4. 更新帖子的pid
        tNotes.setPid(photo.getPid());
        tNotesMapper.updateNotesPhoto(tNotes);
    }

    public void deleteById(Long nid) {
        tNotesMapper.deleteById(nid);
    }


    public void updateBykey(TNotes tNotes) {
        tNotesMapper.updateBykey(tNotes);
    }


    public TNotes selectByNId(Long nid) {
        return tNotesMapper.selectByNId(nid);
    }

    /**
     * 通过本地Uid查询帖子
     * @param uid
     * @return
     */
    public List<TNotes> selectByUid(Integer uid){
        return tNotesMapper.selectByUid(uid);
    }


    public List<TNotes> selectAll() {
        return tNotesMapper.selectAll();
    }


    public PageInfo<TNotes> selectPage(TNotes tNotes, Integer pageNum, Integer pageSize) {
        try{
            PageHelper.startPage(pageNum, pageSize);
            List<TNotes> list = tNotesMapper.selectAll();
            return PageInfo.of(list);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public List<TNotes> findPageByKeys(String keys) {
        return tNotesMapper.findPageByKeys(keys);
    }

}